package org.zjsru.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zjsru.pojo.Payment;
import org.zjsru.pojo.PaymentRecord;
import org.zjsru.service.PaymentService;
import org.zjsru.service.OrderFeignClient;
import org.zjsru.mapper.PaymentMapper;
import org.zjsru.mapper.PaymentRecordMapper;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
public class PaymentServiceImpl implements PaymentService {

    @Autowired
    private PaymentMapper paymentMapper;
    
    @Autowired
    private PaymentRecordMapper paymentRecordMapper;
    
    @Autowired
    private OrderFeignClient orderFeignClient;

    @Value("${payment.timeout:300}")
    private Long paymentTimeout;

    @Override
    @Transactional
    public Payment pay(Long orderId, Long userId, String orderNo, BigDecimal amount) {
        Payment payment = new Payment();
        payment.setPaymentNo(generatePaymentNo());
        payment.setOrderId(orderId);
        payment.setUserId(userId);
        payment.setAmount(amount);
        payment.setStatus(0); // 待支付
        payment.setCreateTime(LocalDateTime.now());
        payment.setUpdateTime(LocalDateTime.now());
        paymentMapper.insert(payment);
        log.info("发起支付，支付单号:{}，订单号:{}", payment.getPaymentNo(), orderNo);
        return payment;
    }

    @Override
    @Transactional
    public boolean paymentCallback(String paymentNo, String callbackContent) {
        Payment payment = paymentMapper.findByPaymentNo(paymentNo);
        if (payment == null) return false;
        
        payment.setStatus(1); // 已支付
        payment.setPayTime(LocalDateTime.now());
        payment.setUpdateTime(LocalDateTime.now());
        paymentMapper.update(payment);
        
        // 记录回调
        PaymentRecord record = new PaymentRecord();
        record.setPaymentId(payment.getId());
        record.setOrderId(payment.getOrderId());
        record.setUserId(payment.getUserId());
        record.setAmount(payment.getAmount());
        record.setStatus(1);
        record.setCallbackContent(callbackContent);
        record.setCallbackTime(LocalDateTime.now());
        record.setCreateTime(LocalDateTime.now());
        paymentRecordMapper.insert(record);
        
        // 调用订单服务更新订单状态
        try {
            boolean orderUpdateResult = orderFeignClient.updateOrderStatus(payment.getOrderId());
            if (orderUpdateResult) {
                log.info("支付成功，订单状态更新成功，支付单号:{}，订单ID:{}", paymentNo, payment.getOrderId());
            } else {
                log.warn("支付成功，但订单状态更新失败，支付单号:{}，订单ID:{}", paymentNo, payment.getOrderId());
            }
        } catch (Exception e) {
            log.error("调用订单服务更新状态失败，支付单号:{}，订单ID:{}", paymentNo, payment.getOrderId(), e);
        }
        
        log.info("支付回调成功，支付单号:{}", paymentNo);
        return true;
    }

    @Override
    public List<PaymentRecord> getPaymentRecordsByOrderId(Long orderId) {
        return paymentRecordMapper.findByOrderId(orderId);
    }

    @Override
    public Payment getPaymentByOrderId(Long orderId) {
        return paymentMapper.findByOrderId(orderId);
    }

    @Override
    @Transactional
    public void handlePaymentTimeout(Long paymentId) {
        Payment payment = paymentMapper.findById(paymentId);
        if (payment == null || payment.getStatus() != 0) return;
        
        payment.setStatus(2); // 超时
        payment.setUpdateTime(LocalDateTime.now());
        paymentMapper.update(payment);
        log.info("支付超时处理，支付单号:{}", payment.getPaymentNo());
    }

    private String generatePaymentNo() {
        return "PAY" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 8);
    }
} 